package springmvc_demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 不同的请求类型, demo
 */
@Controller
public class RequestDemoController {

    //********************************* 请求类型(不带参数) *******************************

    /** Delete请求 */
    @RequestMapping(value = "/request/default", method = RequestMethod.GET)
    public String requestDefault() {
        return "demo/test";
    }

    /** Get请求 */
    @GetMapping("/request/get")
    public String get() {
        return "demo/test";
    }

    /** Post请求 */
    @PostMapping("/request/post")
    public String post() {
        return "demo/test";
    }

    /** Put请求 */
    @PutMapping("/request/put")
    public String put() {
        return "demo/test";
    }

    /** Delete请求 */
    @DeleteMapping("/request/delete")
    public String delete() {
        return "demo/test";
    }

    //********************************* 请求类型(不带参数) end *******************************


    //********************************* 请求参数  *******************************
    /**
     * 默认传参
     * url后面通过问号携带
     * 通过request取
     */
    @GetMapping("/request/param")
    @ResponseBody
    public String param(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        request.getParameterMap().forEach((param,value)->{
            sb.append(param).append(":").append(request.getParameter(param));
            // 为什么value是数组? https://blog.csdn.net/u012730299/article/details/45717365
            sb.append("copy:").append(param).append(":").append(value[0]).append("\r\n");
        });
        if (sb.length()>0){
            return sb.toString();
        }else{
            return "param not found! use?param1=value&param2=2";
        }
    }

    /**
     * 默认传参
     * url后面通过问号携带
     * 通过@requestParam取值(参数默认必传)
     */
    @GetMapping("/request/param1")
    @ResponseBody
    public String param1(@RequestParam String param1, @RequestParam(required=false, defaultValue = "defaultValue") String param2) {
        return "param1:"+param1+",param2:"+param2;
    }

    /** body传参 - 通过@requestParam取值(参数默认必传) */
    @PostMapping("/request/bodyParam")
    @ResponseBody
    public String postParam(@RequestBody String param) {
        return "param:"+param;
    }

    /** path参数 */
    @GetMapping("/request/pathParam/{param}")
    @ResponseBody
    public String pathParam(@PathVariable String param) {
        return "param:"+param;
    }

    /** 综合 */
    @GetMapping("/request/complex/{pathParam}")
    @ResponseBody
    public String complex(@PathVariable String pathParam, @RequestParam String getParam, @RequestBody String requestBody) {
        return "pathParam:"+pathParam +",getParam:"+getParam+", requestBody:"+requestBody;
    }

    //********************************* 请求参数 end *******************************

    //********************************* 文件参数  *******************************
    /**
     * 文件参数
     * 必须配置 multipartResolver
     * 如果需要同时传多个参数, 可以新建一个bean, 其中包含一个MultipartFile属性
     */
    @PostMapping("/request/upload")
    @ResponseBody
    public String upload(MultipartFile file, HttpSession session) throws IOException {
        String originalFilename = file.getOriginalFilename();
        if (originalFilename==null){
            throw new RuntimeException("读取文件失败!");
        }

        String realPath = session.getServletContext().getRealPath("uploads");
        File folder = new File(realPath + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        if (!folder.exists()) {
            if (!folder.mkdirs()){
                throw new RuntimeException("目录创建失败!");
            }
        }

        // 存储文件
        String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        File outFilePath = new File(folder, new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "." + ext);
        file.transferTo(outFilePath);

        return "success! filePath:"+outFilePath.getPath();
    }
    //********************************* 文件参数 end *******************************

}
